<template>
  <div class="container">
    <city-selector v-model="addressInfo.areas" @onSelectedAddrTextChange="onSelectedAddrTextChange" :visible="isSelectCity" @on-visible-change="onVisibleChange"></city-selector>
    <div class="bg-white rel" v-if="currentAddr && currentAddr.username" @click="isAddrSelectDialogShowed=true">
      <div class="p1">
        <div class="flex">
          <div class="flex-con reciver one-line">收货人：{{currentAddr.username}}</div>
          <div>{{currentAddr.mobile}}</div>
        </div>
        <div class="flex address">
          <img src="../../assets/icons/loc-gray.png" alt="" class="loc-gray">
          <div class="flex-con">收货地址：{{currentAddr.fulladdress}}</div>
          <img src="../../assets/icons/gt.png" alt="" class="gt">
        </div>
      </div>
      <img src="../../assets/icons/line-red-blue.png" alt="" class="redblueline">
    </div>
    <template v-else>
      <div class="bg-white rel text-center add-new-addr-area">
        <div class="add-new-addr-btn" @click="isAddAddrSelectDialogShowed=true">
          + 新增地址
        </div>
      </div>
      <div class="hr24-gray"></div>
    </template>

    <div v-for="(shop,index) in shops" :key="index">
      <!-- <div class="hr24-gray"></div>
      <div class="title-p">
        <div class="flex">
          <img src="../../assets/icons/zyicon.png" alt="" class="zyicon">
          <div class="zy-title">
            {{shop.providerName||'中油BP'}}
          </div>
        </div>
      </div> -->
      <div class="goods-item" v-for="item in shop.items" :key="item.id">
        <div class="flex" @click="gotoShop(item.goodsId)">
          <div class="goods1-img bg-img-contained" :style="'background-image:url('+ (imgUrl(item.goodsCover))  +')'"></div>
          <div class="goods-item-desc flex-con">
            <div class="goods-item-title">
              <div class="flex">
                <div class="flex-con goods-title two-line">
                  {{item.goodsTitle}}
                </div>
                <div class="goods-points">
                  {{item.points}}积分+{{item.price}}元
                </div>
              </div>
            </div>
            <div class="goods-item-rule">
              <div class="flex">
                <div class="flex-con goods-rule">
                  <template v-if="item.goodsRules">
                    规格：{{item.goodsRules}}
                  </template>
                </div>
                <div class="goods-num">
                  X {{item.num}}
                </div>
              </div>
            </div>
          </div>
        </div>
      </div>
    </div>


    <div class="list-item border-b" @click="isExpressSelectDialogShowed=true">
      <div class="flex">
        <div class="list-item-label">
          配送方式
        </div>
        <div class="flex-con text-right">
          快递免邮
        </div>
        <img src="../../assets/icons/gt.png" alt="" class="gt">
      </div>
    </div>
    <label class="list-item border-b block">
      <div class="flex">
        <div class="list-item-label">
          给买家留言：
        </div>
        <div class="flex-con">
          <input type="text" class="words" v-model="words" placeholder="点击给商家留言">
        </div>
      </div>
    </label>
    <!-- <div class="list-item border-b">
      <div class="flex">
        <div class="list-item-label">
          优惠券码
        </div>
        <div class="flex-con text-right txt999">
          使用优惠
        </div>
        <img src="../../assets/icons/gt.png" alt="" class="gt">
      </div>
    </div> -->
    <div class="list-item border-b goods-money-info">
      <div class="flex">
        <div class="list-item-label">
          商品总额
        </div>
        <div class="flex-con text-right color3">
          <span class="goods-points">{{totalPoints}}积分</span>+{{totalMoney}}元
        </div>
      </div>
      <div class="flex">
        <div class="list-item-label">
          运费
        </div>
        <div class="flex-con text-right color3">
          0 元
        </div>
      </div>
      <div class="flex">
        <div class="list-item-label">
          优惠
        </div>
        <div class="flex-con text-right color3">
          - 0 元
        </div>
      </div>
    </div>
    <!-- <div class="list-item border-b">
      <div class="flex">
        <div class="list-item-label">
          开具发票
        </div>
        <div class="flex-con text-right txt999">
          需要发票
        </div>
        <img src="../../assets/icons/gt.png" alt="" class="gt">
      </div>
    </div> -->
    <div class="masker" v-if="isExpressSelectDialogShowed" @click="isExpressSelectDialogShowed=false">
      <div class="dialog new-addr-dialog" @click.stop="noop">
        <div class="dialog-title border-b">
          配送方式
          <img src="../../assets/icons/bill/closebtn@2x.png" alt="" class="dialog-closebtn" @click="isExpressSelectDialogShowed=false">
        </div>
        <div class="express-item" @click="toggleExpressType">
          <div class="flex">
            <div class="flex-con fz28 txt333">快递 免邮</div>
            <div>
              <img src="../../assets/icons/bill/okselected@2x.png" alt="" class="ok-selected-icon">
            </div>
          </div>
        </div>
      </div>
    </div>

    <div class="masker" v-if="isAddrSelectDialogShowed" @click="isAddrSelectDialogShowed=false">
      <div class="dialog addr-dialog" @click.stop="noop">
        <div class="dialog-title border-b">
          选择收货地址
          <img src="../../assets/icons/bill/closebtn@2x.png" alt="" class="dialog-closebtn" @click="isAddrSelectDialogShowed=false">
        </div>

        <div class="dialog-item border-b" v-for="(addr,addrindex) in addrList" :key="addr.id" @click.stop="toggleAddrSelected(addr)">
          <mt-cell-swipe class="cell-swipe" :right="[
          {
            content: '删除',
            style: { background: 'red', color: '#fff'},
            handler: () => deleteCartItem(addr.id,addrindex)
          }
        ]">
            <div class="flex addr-item">
              <div>
                <img v-if="addr.isdefault==1" src="../../assets/icons/bill/selected@2x.png" alt="" class="selected-img" />
                <img v-else src="../../assets/icons/bill/notselected@2x.png" alt="" class="selected-img" />
              </div>
              <div class="flex-con">
                <div class="flex flex-stretch">
                  <div class="flex-con">
                    <div class="addr-username">收货人：{{addr.username}}</div>
                    <div class="addr-detail">收货地址：{{addr.fulladdress}}</div>
                  </div>

                </div>
              </div>
              <div class="edit-area flex" @click.stop="editAddr(addr)">
                <img src="../../assets/icons/bill/comment@2x.png" alt="" class="comment-icon">
              </div>
            </div>
          </mt-cell-swipe>
        </div>

        <div class="add-addr-item" @click="isAddAddrSelectDialogShowed=true">
          <div class="flex">
            <div>
              <img src="../../assets/icons/bill/addaddr@2x.png" alt="" class="addaddr-icon">
            </div>

            <div class="flex-con">
              新增地址
            </div>
            <img src="../../assets/icons/gt.png" alt="" class="gt">
          </div>
        </div>
      </div>
    </div>

    <div class="masker" v-if="isAddAddrSelectDialogShowed" @click="isAddAddrSelectDialogShowed=false">
      <div class="dialog new-addr-dialog" @click.stop="noop">
        <div class="dialog-title border-b">
          新建收货地址
          <img src="../../assets/icons/bill/closebtn@2x.png" alt="" class="dialog-closebtn" @click="isAddAddrSelectDialogShowed=false">
        </div>
        <label class="p30 border-b block">
          <div class="flex">
            <div class="label">
              收货人
            </div>
            <div class="flex-con">
              <input type="text" v-model="addressInfo.username" class="addr-input" placeholder="名字">
            </div>
          </div>
        </label>
        <label class="p30 border-b block">
          <div class="flex">
            <div class="label">
              联系电话
            </div>
            <div class="flex-con">
              <input type="tel" v-model="addressInfo.mobile" class="addr-input" placeholder="手机或固定电话">
            </div>
          </div>
        </label>
        <label class="p30 border-b block" @click="isSelectCity=true">
          <div class="flex">
            <div class="label">
              选择地区
            </div>
            <div class="flex-con text-right">
              {{addressInfo.areasName||'请选择'}}
            </div>
            <img src="../../assets/icons/gt.png" alt="" class="gt">
          </div>
        </label>
        <label class="p30 block border-b">
          <div class="flex">
            <div class="label">
              详细地址
            </div>
            <div class="flex-con">
              <input type="text" v-model="addressInfo.detailaddress" class="addr-input" placeholder="请填写详细地址">
            </div>
          </div>
        </label>
        <label class="p30 block border-b">
          <div class="flex">
            <div class="label">
              邮政编码
            </div>
            <div class="flex-con">
              <input type="tel" v-model="addressInfo.postcode" class="addr-input" placeholder="请填写邮政编码">
            </div>
          </div>
        </label>
        <div class="save-btn-area">
          <div class="save-btn" @click="addNewAddr">
            保存
          </div>
        </div>
      </div>
    </div>

    <div class="footer-nav-before"></div>
    <div class="footer-nav flex">
      <div class="sum-info flex-con text-right">
        合计：
        <span class="goods-points">{{totalPoints}}积分</span>
        <span class="color3">+{{totalMoney}}元</span>
      </div>
      <div class="submit-btn" @click="submitBill">
        提交订单
      </div>
    </div>
  </div>
</template>
<script>
import citySelectorVue from "../../components/citySelector";
import { isValidPostCode, isValidMobilePhone } from '../../utils/common';

let wx = require("weixin-js-sdk");

export default {
  components: {
    "city-selector": citySelectorVue
  },
  data() {
    return {
      isSelectCity: false,
      addressInfo: {
        areas: [],
        areasName: ""
      },
      isAddrSelectDialogShowed: false,
      currentAddr: null,
      addrList: [],
      isExpressSelectDialogShowed: false,
      shops: [],
      words: "",
      totalPoints: 0,
      totalMoney: 0,
      isAddAddrSelectDialogShowed: false
    };
  },
  methods: {
    deleteCartItem(id, index) {
      this.$messagebox
        .confirm("确定删除该地址吗?")
        .then(action => {
          this.showLoading();
          this.$post("/api/user/address/delete", {
            id
          })
            .then(el => {
              this.hideLoading();
              if (this.addrList[index].isdefault == true) {
                this.currentAddr = [];
              }
              this.addrList.splice(index, 1);
              if (this.addrList.length == 0) {
                this.currentAddr = [];
              }
            })
            .catch(_ => {
              this.hideLoading();
            });
        })
        .catch(el => {});
    },
    toggleAddrSelected(addr) {
      addr.isdefault = true;
      this.currentAddr = addr;
      this.addrList &&
        this.addrList.forEach(el => {
          if (el.id == addr.id) {
            return;
          }
          el.isdefault = false;
        });
    },
    editAddr(addr) {
      this.addressInfo = addr;
      this.isAddAddrSelectDialogShowed = true;
    },
    gotoShop(id) {
      this.$router.push("/goodsdetail?id=" + id);
    },
    onSelectedAddrTextChange(titles) {
      this.addressInfo.areasName = titles.join(" ");
    },
    addNewAddr() {
      if (this.isEmpty(this.addressInfo.username)) {
        this.$toast("请填写收货人");
        return;
      }
      if (this.isEmpty(this.addressInfo.mobile)) {
        this.$toast("请填写联系电话");
        return;
      }
      if (!isValidMobilePhone(this.addressInfo.mobile)) {
        this.$toast("请填写正确的联系电话");
        return;
      }
      if (this.isEmpty(this.addressInfo.areas)) {
        this.$toast("请选择地区");
        return;
      }
      if (this.isEmpty(this.addressInfo.detailaddress)) {
        this.$toast("请填写详细地址");
        return;
      }
      if (this.isEmpty(this.addressInfo.postcode)) {
        this.$toast("请填写邮编号码");
        return;
      }
      if (!isValidPostCode(this.addressInfo.postcode)) {
        this.$toast("请填写正确的邮编号码");
        return;
      }
      this.addressInfo.fulladdress =
        this.addressInfo.areasName.replace(/\s/g, "") +
        this.addressInfo.detailaddress;
      this.showLoading();
      this.$post("/api/user/addNewAddr", this.addressInfo)
        .then(res => {
          this.addrList &&
            this.addrList.forEach(el => {
              el.isdefault = false;
            });
          this.addressInfo.isdefault = true;
          this.addressInfo.id = res;
          this.currentAddr = this.addressInfo;
          this.addrList.push(this.addressInfo);
          this.addressInfo = {
            areas: [],
            areasName: ""
          };
          this.isAddAddrSelectDialogShowed = false;
          this.hideLoading();
        })
        .catch(res => {
          this.hideLoading();
        });
    },
    onVisibleChange(v) {
      this.isSelectCity = v;
    },
    onBridgeReady(info) {
      let that = this;
      WeixinJSBridge.invoke(
        "getBrandWCPayRequest",
        {
          appId: info.appId, //公众号名称，由商户传入
          timeStamp: info.timeStamp, //时间戳，自1970年以来的秒数
          nonceStr: info.nonceStr, //随机串
          package: info.packageValue,
          signType: info.signType, //微信签名方式：
          paySign: info.paySign //微信签名
        },
        function(res) {
          // 使用以上方式判断前端返回,微信团队郑重提示：res.err_msg将在用户支付成功后返回ok，但并不保证它绝对可靠。
          if (res.err_msg == "get_brand_wcpay_request:ok") {
            that.$router.push("/bill?type=1");
          } else {
            that.$router.push("/bill?type=0"); //取消就跳转到待支付页面
          }
        }
      );
    },
    dopay(data) {
      //order_id
      var vm = this;
      if (typeof WeixinJSBridge == "undefined") {
        //微信浏览器内置对象。参考微信官方文档
        if (document.addEventListener) {
          document.addEventListener(
            "WeixinJSBridgeReady",
            vm.onBridgeReady(data),
            false
          );
        } else if (document.attachEvent) {
          document.attachEvent("WeixinJSBridgeReady", vm.onBridgeReady(data));
          document.attachEvent("onWeixinJSBridgeReady", vm.onBridgeReady(data));
        }
      } else {
        vm.onBridgeReady(data);
      }
    },
    preparePay(order_id, callback) {
      this.$post("/api/wx/wxpay", {
        orderId: order_id
      })
        .then(data => {
          if(data){
            this.dopay(data); 
          }else{
             this.$router.replace("/bill?type=1");
            
          }
          callback && callback();
        })
        .catch(_ => {
          callback && callback();
        });
    },
    submitBill() {
      if (!this.currentAddr || this.currentAddr.id < 1) {
        this.$toast("请填写收货地址");
        return;
      }
      let cartIds = this.$route.params.cartIds;
      let goodsNum = parseInt(this.$route.query.goodsNum);
      if (goodsNum > 0) {
        let goodsRuleToken = (this.$route.query.goodsRuleToken || "").trim();
        this.showLoading();
        this.$post("/api/wx/create_order", {
          goodsId: parseInt(cartIds),
          goodsRuleToken: goodsRuleToken,
          goodsNum: goodsNum,
          addrId: this.currentAddr.id,
          words: this.words.trim()
        })
          .then(info => {
            this.preparePay(info, _ => {
              this.hideLoading();
            });
          })
          .catch(() => {
            this.hideLoading();
          });
        return;
      }
      this.showLoading();
      this.$post("/api/wx/create_order", {
        cartIds,
        addrId: this.currentAddr.id,
        words: this.words.trim()
      })
        .then(info => {
          this.preparePay(info, _ => {
            this.hideLoading();
          });
        })
        .catch(() => {
          this.hideLoading();
        });
    },
    toggleExpressType() {
      this.isExpressSelectDialogShowed = false;
    }
  },
  mounted() {
    this.$post("/api/user/address/list").then(data => {
      if (data && data.length) {
        let defaultAddr = data[0];
        data.forEach(el => {
          if (el.isdefault == 1) {
            defaultAddr = el;
          }
        });
        this.currentAddr = defaultAddr;
        this.addrList = data;
      }
    });
    let cartIds = this.$route.params.cartIds;
    let goodsRuleToken = this.$route.query.goodsRuleToken;
    let goodsNum = parseInt(this.$route.query.goodsNum);
    let loadData = info => {
      this.loaded = true;
      this.hideLoading();
      info = info || [];
      if (info.length) {
        let map = {};
        for (let item of info) {
          if (!map[item.providerId]) {
            map[item.providerId] = {
              items: [],
              providerName: item.providerName
            };
          }
          map[item.providerId].items.push(item);
        }
        for (let key in map) {
          this.shops.push(map[key]);
        }

        let points = 0;
        let price = 0;
        this.shops.forEach(shop => {
          shop.items.forEach(item => {
            points += item.points * item.num;
            price += item.price * item.num;
          });
        });
        this.totalMoney = price.toFixed(2);
        this.totalPoints = points;
      }
    };
    if (goodsRuleToken && goodsNum > 0) {
      goodsRuleToken = goodsRuleToken.trim();
      this.showLoading();
      this.$post("/api/user/getGoodsByGoodsRuleToken", {
        goodsRuleToken,
        goodsNum,
        goodsId: cartIds
      })
        .then(info => {
          loadData(info);
        })
        .catch(() => {
          this.hideLoading();
        });
      return;
    } else if (goodsNum > 0) {
      // 立即购买商品
      this.showLoading();
      this.$get("/api/user/getGoodsById", {
        goodsId: parseInt(cartIds),
        goodsNum
      })
        .then(info => {
          loadData(info);
        })
        .catch(() => {
          this.hideLoading();
        });
      return;
    }
    if (cartIds) {
      this.showLoading();
      this.$get("/api/user/getCart", {
        cartIds
      })
        .then(info => {
          loadData(info);
        })
        .catch(() => {
          this.hideLoading();
        });
    }
  }
};
</script>

<style lang="scss" scoped>
.goods-item {
  background-color: #f1f0f0;
  padding: 0.2rem 0.4rem;
  .goods-points {
    font-size: 0.2667rem;
    color: #909b95;
  }
}

.redblueline {
  width: 100%;
  position: absolute;
  left: 0;
  bottom: 0;
}

.express-item {
  padding: 0.48rem 0.4rem 1.5067rem 0.4rem;
  .ok-selected-icon {
    width: 0.4933rem;
    height: 0.4933rem;
  }
}

.edit-area {
  width: 1.5rem;
  text-align: right;
  margin-right: 0.3rem;
  justify-content: flex-end;
}

.save-btn-area {
  padding: 0.8667rem 0 0.7733rem 0;
  text-align: center;
  .save-btn {
    color: #ff2a2a;
    font-size: 0.3733rem;
    width: 6.08rem;
    height: 0.9067rem;
    line-height: 0.8533rem;
    box-sizing: border-box;
    border: 0.0267rem solid #ff2a2a;
    border-radius: 0.14rem;
    margin: 0 auto;
  }
}

.add-new-addr-area {
  padding: 0.6rem 0;
}

.add-new-addr-btn {
  font-size: 0.4rem;
  border: 1px solid #005a1a;
  color: #005a1a;
  width: 4rem;
  margin: 0 auto;
  padding: 0.2667rem 0;
}

.new-addr-dialog {
  .label {
    width: 2.4rem;
  }
  .addr-input {
    width: 100%;
    outline: none;
  }
}

.goods1-img {
  width: 3.3733rem;
  height: 2.1733rem;
}

.p1 {
  padding: 0.5067rem 0.4133rem 0.72rem 0.4rem;
  font-size: 0.3733rem;
}

.hr24-gray {
  height: 0.1333rem;
  background-color: #f1f0f0;
}

.address {
  padding-top: 0.4133rem;
}

.reciver {
  padding-left: 0.6533rem;
}

.footer-nav-before {
  height: 1.2267rem;
}

.list-item {
  font-size: 0.3467rem;
}

.sum-info {
  font-size: 0.3733rem;
  padding: 0 0.2667rem;
}

.zyicon {
  width: 0.4667rem;
  height: 0.48rem;
  margin-right: 0.1867rem;
}

.title-p {
  padding: 0.32rem 0.4rem;
}

.zy-title {
  font-size: 0.32rem;
}

.goods-points {
  color: #ff2a2a;
  font-size: 0.3733rem;
}

.color3 {
  font-size: 0.3733rem;
  color: #005a1a;
}

.footer-nav {
  height: 1.2267rem;
  position: fixed;
  left: 0;
  bottom: 0;
  right: 0;
  background-color: #efefef;
}

.submit-btn {
  background-color: #e82f24;
  width: 3.16rem;
  height: 1.2267rem;
  line-height: 1.2267rem;
  font-size: 0.4rem;
  color: #ffffff;
  text-align: center;
}

.loc-gray {
  width: 0.3067rem;
  height: 0.4267rem;
  margin-right: 0.3467rem;
}

.goods-title {
  font-size: 0.3467rem;
  color: #17402a;
}

.dialog >>> .cell-swipe {
  display: block;
}

.goods-item-rule {
  padding-top: 0.4267rem;
}

.goods-rule {
  font-size: 0.2933rem;
}

.goods-num {
  font-size: 0.2933rem;
  color: rgba(23, 64, 42, 0.57);
}

.goods-item-desc {
  padding-left: 0.2533rem;
}

.list-item {
  padding: 0.4rem;
}

.gt {
  margin-left: 0.32rem;
}

.goods-money-info {
  line-height: 0.7467rem;
}

.words {
  width: 100%;
  outline: none;
}

.masker {
  position: fixed;
  background-color: rgba(0, 0, 0, 0.36);
  left: 0;
  right: 0;
  z-index: 10;
  top: 0;
  bottom: 0;
  .dialog {
    position: fixed;
    bottom: 0;
    left: 0;
    font-size: 0.3733rem;
    right: 0;
    background-color: #fff;
  }
  .dialog-title {
    font-size: 0.4267rem;
    color: #222222;
    text-align: center;
    padding: 0.3467rem 0;
  }
  .dialog-closebtn {
    width: 0.5067rem;
    height: 0.5067rem;
    position: absolute;
    right: 0.4rem;
    top: 0.2933rem;
  }
  .selected-img {
    width: 0.44rem;
    height: 0.44rem;
    margin-right: 0.3467rem;
  }
  .dialog-item {
    padding: 0 0 0 0.4rem;
    .flex.addr-item {
      width: 100%;
    }
    .flex.addr-item > div {
      padding: 0.52rem 0;
    }
  }

  .addr-username {
    font-size: 0.3733rem;
    color: #333333;
    padding-bottom: 0.3467rem;
  }
  .addr-detail {
    font-size: 0.32rem;
    color: #999999;
  }
  .comment-icon {
    width: 0.5467rem;
    height: 0.5333rem;
  }
  .add-addr-item {
    padding: 0.4933rem 0.4rem;
    .addaddr-icon {
      width: 0.3867rem;
      height: 0.3867rem;
      margin-right: 0.4rem;
    }
  }
}
</style>
